 
package com.zdkj.subway.rca.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.core.util.R;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.rca.dto.out.SwCkClearRulesExcelDTO;
import com.zdkj.subway.rca.entity.SwCkClearRules;
import com.zdkj.subway.rca.entity.SwCkClearRulesLine;
import com.zdkj.subway.rca.entity.ViewCkClearAccountDetailSummary;
import com.zdkj.subway.rca.entity.ViewCkSystemCleanView;
import com.zdkj.subway.rca.mapper.ViewCkSystemCleanViewMapper;
import com.zdkj.subway.rca.service.ViewCkSystemCleanViewService;
import com.zdkj.subway.rca.util.LocalDateConverter;
import com.zdkj.subway.rca.util.LocalDateTimeConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统清分数据展示
 *
 * @author cooze
 * @date 2020-11-03 21:46:31
 */
@Service
@Slf4j
public class ViewCkSystemCleanViewServiceImpl extends ServiceImpl<ViewCkSystemCleanViewMapper, ViewCkSystemCleanView> implements ViewCkSystemCleanViewService {


    @Override
    public void export(String startDate, String endDate, String lineCode, HttpServletResponse response) {
        ViewCkSystemCleanView viewCkSystemCleanView = new ViewCkSystemCleanView();
        if(StringUtils.isNotEmpty(lineCode)){
            viewCkSystemCleanView.setLineCode(lineCode);
        }
        boolean isDateCondition = StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate);
        List<ViewCkSystemCleanView> records = baseMapper.selectList(Wrappers.query(viewCkSystemCleanView)
                .lambda().between(isDateCondition, ViewCkSystemCleanView::getTradeDate, startDate, endDate).orderByAsc(ViewCkSystemCleanView::getTradeDate));
		//获取线路编号和名称（二期名称和运营参与方ID）
		List<Map<String,String>> stationObjList = this.baseMapper.selectStationMap();
        /*
        Map<String, String> map = new HashMap<>();
        map.put("41","1号线一期");
        map.put("42","2号线");
        map.put("43","3号线");
        map.put("44","4号线");
        map.put("45","5号线一期");
        map.put("46","6号线");
        map.put("49","9号线");
        map.put("54","机场城际");
        map.put("71","1号线二期");
        map.put("72","5号线二期");*/
        records.stream().forEach(x ->{			
            x.setLineCode(getExportLineName(stationObjList,x.getLineCode()));
        });
        InputStream excelTemplateIs = null;
        try {response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("系统清分数据展示表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
            // {} 代表普通变量 {.} 代表是list的变量

            excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/export/ViewCkSystemCleanViewExcelTemplate.xlsx");

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("系统清分数据展示表").build();
            // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
            // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
            // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
            // 如果数据量大 list不是最后一行 参照另一个
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            excelWriter.fill(records, fillConfig, writeSheet);

            excelWriter.finish();

        } catch (Exception e) {
            e.printStackTrace();
            log.error("导出系统清分数据展示表异常");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }

	private String getExportLineName (List<Map<String,String>> lineMap,String lineCode) {
      
        for (Map<String,String> map : lineMap) {
            if(lineCode.equals(map.get("CODE"))) {
                return map.get("NAME");
            }
        }
        return "";
    }
}
